//
//  override_func.hpp
//  learnC++
//
//  Created by liuzhibing on 2018/6/15.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#ifndef override_func_hpp
#define override_func_hpp

#include <stdio.h>
#include <iostream>

class A1
{
public:
    virtual const char* getName1(int x) { return "A"; }
    virtual const char* getName2(int x) { return "A"; }
    virtual const char* getName3(int x) { return "A"; }
};

class B1 /*final*/  : public A1
{
public:
//    override相当于重写虚函数，可以用作提醒，如果基类没有重写的函数会编译报错
//    virtual const char* getName1(short int x) override { return "B"; } // compile error, function is not an override
//    virtual const char* getName2(int x) const override { return "B"; } // compile error, function is not an override
    virtual const char* getName3(int x) override /*final*/ { return "B"; } // okay, function is an override of A::getName3(int)
    //你可以加上final终止符，防止继承该类的类重写该方法,如果后面的类重写了，就会编译报错
};


//在我们想阻止从类继承的情况下，最后的说明符应用在类名后面：
class C1 : public B1 {
    
    
public:
    virtual const char* getName3(int x) override { return "B"; }
};

/*
 //较为特殊的情况基类指向派生类，基类调用派生类的虚函数，返回的派生类的指针会被默认转化为基类类型
 class Base
 {
 public:
 // This version of getThis() returns a pointer to a Base class
 
 virtual Base* getThis() { std::cout << "called Base::getThis()\n"; return this; }
 
 void printType() { std::cout << "returned a Base\n"; }
 };
 
 class Derived : public Base
 {
 public:
 // Normally override functions have to return objects of the same type as the base function
 // However, because Derived is derived from Base, it's okay to return Derived* instead of Base*
 
 virtual Derived* getThis() { std::cout << "called Derived::getThis()\n";  return this; }
 
 void printType() { std::cout << "returned a Derived\n"; }
 };
 
 int main()
 {
 Derived d;
 Base *b = &d;
 d.getThis()->printType(); // calls Derived::getThis(), returns a Derived*, calls Derived::printType
 b->getThis()->printType(); // calls Derived::getThis(), returns a Base*, calls Base::printType
 }
 This prints:
 
 called Derived::getThis()
 returned a Derived
 called Derived::getThis()
 returned a Base
 
 
 */


#endif /* override_func_hpp */
